home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11061 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news.sinet.slb.com!usenet
  2. From: "Vinh D. Nguyen" <vnguyen@sugar-land.anadrill.slb.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Dynamic alloc of 2D array??
  5. Date: Tue, 12 Mar 1996 08:29:52 -0600
  6. Organization: Schlumberger Anadrill
  7. Message-ID: <31458A60.17E0@sugar-land.anadrill.slb.com>
  8. References: <4hpjbo$fsb@masala.cc.uh.edu>
  9. NNTP-Posting-Host: 163.185.118.40
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (WinNT; I)
  14.  
  15. sukumar wrote:
  16. > char** cities;
  17. > // Alloc x number of char*s
  18. > cities = new (char* [x]);
  19. > for(i=0; i<x; i++)
  20. >     delete [] cities[i];
  21. > delete [] cities;
  22. > The program crashes when I don't assign anything to the cities.
  23. > What is the right way to alloc an array of pointers and delete them??
  24. > TIA,
  25. > SK
  26.  
  27. Your program crashed because you did not initialize the cities array to NULL.
  28. Objects (variables, arrays, etc.) in C and C++ are on initialized upon creation,
  29. so without initialization, your cities array contain garbage values. When you attempt
  30. to destroy the entries in cities, you are trying to deallocate memory pointed at
  31. by these garbage values. The correct way to avoid this problem is to initialize cities
  32. to NULL as follows:
  33.  
  34. cities = new char * [ x ];
  35. memset( cities, 0, x * sizeof( char * ) );
  36.  
  37. The delete operator becomes a no-op when operated on a NULL pointer.
  38.  
  39. Hope this helps.
  40.  
  41. -- 
  42. --------------------------------------------------------------------------
  43. * Vinh Nguyen                                            vnguyen@slb.com *
  44. * Drilling Information Products - Senior Engineer                        *
  45. * Anadrill Schlumberger                             *
  46. * 200 Gillingham Ln.                             (713) 275-7524 (Office) *
  47. * Sugarland, TX 77478                            (713) 275-8098 (FAX)    *
  48. --------------------------------------------------------------------------
  49.